<template>
  <div>
    <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="id" border>
      <el-table-column prop="id" label="用户编号" sortable width="180"></el-table-column>
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column prop="rolename" label="所属角色" width="180"></el-table-column>
      <el-table-column label="状态" width="180">
        <template v-slot="scope">
          <el-button v-if="scope.row.status === 1" type="success">启用</el-button>
          <el-button v-else type="danger">禁用</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button type="success" @click="edit(scope.row.uid)">编辑</el-button>
          <el-button type="danger" @click="del(scope.row.uid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="pageChange"
      :page-size="userl.size"
      background
      layout="prev, pager, next"
      :total="total"
    ></el-pagination>
  </div>
</template>

<script>
import { userList, delUser, userTotal } from "../../../request/api";
import { successAlert } from "../../../utils/alert";

export default {
  data() {
    return {
      tableData: [],
      userl: {
        size: 2,
        page: "1"
      },
      total: 1
    };
  },
  watch: {
    userl: {
      handler(newVal) {
        this.requestUserList();
      },
      deep: true
    }
  },
  methods: {
    requestUserList() {
      userList(this.userl).then(res => {
        if (res.code === 200) {
          this.tableData = res.list;
        }
      });
    },
    edit(uid) {
      this.$emit("edit", uid);
    },
    del(uid) {
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 发起删除请求
          delUser({ uid }).then(res => {
            if (res.code === 200) {
              successAlert(res.msg);
              userList(this.userl).then(res => {
                if (!res.list&&this.userl.page>1) {
                  this.userl.page--;
                }
                this.getTotal();
                this.requestUserList();
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    pageChange(page) {
      this.userl.page = page;
    },
    getTotal() {
      userTotal().then(res => {
        // console.log(res);
        this.total = res.list[0].total;
        // console.log(this.total);
      });
    }
  },
  mounted() {
    this.requestUserList(); //获取管理员列表
    this.getTotal();
    this.$eventBus.$on("message", () => {
      this.requestUserList();
      this.getTotal();
    });
  }
};
</script>

<style>
</style>